﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Anaida
{
    public class HTTPRequestParser
    {

        private byte[] buffer = new byte[0];
        private byte[] separator = new byte[] { 13, 10 };


        public void AddToBuffer(byte[] part)
        {
            int length = buffer.Length + part.Length;
            byte[] buffer2 = new byte[length];
            System.Array.Copy(buffer, 0, buffer2, 0, buffer.Length);
            System.Array.Copy(part, 0, buffer2, buffer.Length, part.Length);
            buffer = buffer2;
        }

        public byte[] getALine()
        {
            if (buffer.Length < separator.Length) return null;
            byte[] result = null;
            int i = ContainsPacket();
            if (i != -1)
            {
                result = GetNBytes(i, this.separator);
            }
            return result;
        }

        public int ContainsPacket()
        {
            for (int i = 0; i < buffer.Length - separator.Length + 1; i++)
            {
                bool match = true;
                for (int j = 0; j < separator.Length; j++)
                {
                    if (buffer[i + j] != separator[j])
                    {
                        match = false;
                        break;
                    }
                }
                if (match)
                {
                    return i;
                }
            }
            return -1;
        }

        public byte[] GetNBytes(int i, byte[] sep)
        {
            byte[] result;
            result = new byte[i];
            System.Array.Copy(buffer, 0, result, 0, i);
            //System.out.println("Result:"+new String(result));//@%#$%$#%$#%$#%#$%$#
            byte[] buffer2 = new byte[buffer.Length - i - sep.Length];
            System.Array.Copy(buffer, i + sep.Length, buffer2, 0, buffer2.Length);
            buffer = buffer2;
            return result;
        }


        public void SetSeparator(byte[] separator)
        {
            this.separator = separator;
        }

        public byte[] GetBuffer()
        {
            return buffer;
        }



    }
}
